﻿using Microsoft.Extensions.Configuration;
using OConf.Common;
using OConf.Entity;
using OConf.IBLL;
using OConf.Model;
using OConf.Model.Common;
using OConf.Model.RequestInput.ProjectInfo;
using OConf.Service;
using System;
using System.Collections.Generic;
using System.Linq;

namespace OConf.BLL
{
    public class VersionsBLL: IVersionsBLL
    {
        private readonly IConfiguration _configuration;
        private readonly VersionsService _versionsService;
        private readonly ConfigInfoHistoryService _configInfoHistoryService;
        private readonly CNameSpaceService _cNameSpaceService;
        private readonly ProjectInfoService _projectInfoService;
        public VersionsBLL(IConfiguration configuration)
        {
            _configuration = configuration;
            _versionsService = new VersionsService(configuration);
            _configInfoHistoryService = new ConfigInfoHistoryService(configuration);
            _cNameSpaceService = new CNameSpaceService(configuration);
            _projectInfoService = new ProjectInfoService(configuration);
        }

        /// <summary>
        /// 获取命名空间下的版本信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ReturnData<List<VersionsModel>> GetVersions(GetVersionsInput input)
        {
            try
            {
                List<VersionsModel> result = _versionsService.GetListByNameSpaceId(input.NameSpaceID)
                    .Select(w => new VersionsModel()
                    {
                        ID = w.ID,
                        VersionNo = w.VersionNo,
                        Createtime = w.Createtime
                    }).ToList();

                return ReturnDataHelper<List<VersionsModel>>.Success("操作成功", result);
            }
            catch (Exception ex)
            {
                Log4NetHelper.WriteExceptionLog("GetVersions,获取命名空间下的版本信息", ex);
                return ReturnDataHelper<List<VersionsModel>>.Exception("系统异常", null);
            }
        }

        /// <summary>
        /// 版本回滚
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ReturnData<BackProgramConfigInfo> VersionRollBack(VersionRollBackInput input)
        {
            try
            {
                VersionsEntity oldVersion = _versionsService.GetModel(input.VersionID);
                if (oldVersion == null)
                {
                    return ReturnDataHelper<BackProgramConfigInfo>.NoExists("版本信息不存在", null);
                }

                CNameSpaceEntity cNameSpace = _cNameSpaceService.FindEntity(oldVersion.NameSpaceID);
                if (cNameSpace == null)
                {
                    return ReturnDataHelper<BackProgramConfigInfo>.NoExists("命名空间不存在", null);
                }

                List<ConfigInfoHistoryEntity> configInfoHistories = _configInfoHistoryService.GetListByVersionId(input.VersionID);

                long nowTime = TimeCore.GetNowTimeOffset();
                DateTime now = DateTime.Now;

                VersionsEntity newVersion = new VersionsEntity()
                {
                    ID = Guid.NewGuid().ToString("N"),
                    ProjectID = oldVersion.ProjectID,
                    NameSpaceID = oldVersion.NameSpaceID,
                    VersionNo = $"{cNameSpace.NameSpace}-{nowTime}",
                    Createtime = now
                };

                List<ConfigInfoHistoryEntity> newConfigInfoHistories = configInfoHistories.Select(w => new ConfigInfoHistoryEntity()
                {
                    ID = Guid.NewGuid().ToString("N"),
                    VersionID = newVersion.ID,
                    ConfigKey = w.ConfigKey,
                    ConfigValue = w.ConfigValue,
                    ConfigDescription = w.ConfigDescription
                }).ToList();

                List<ConfigInfoEntity> configInfos = configInfoHistories.Select(w => new ConfigInfoEntity()
                {
                    ID = Guid.NewGuid().ToString("N"),
                    ProjectID = cNameSpace.ProjectID,
                    NameSpaceID = cNameSpace.ID,
                    ConfigKey = w.ConfigKey,
                    ConfigValue = w.ConfigValue,
                    ConfigDescription = w.ConfigDescription,
                    CreateTime = now,
                    State = (int)ConfigInfoState.已发布
                }).ToList();

                _versionsService.VersionRollBackByTran(newVersion, newConfigInfoHistories, configInfos);

                ProjectInfoEntity projectInfo = _projectInfoService.FindEnity(oldVersion.ProjectID);
                if (projectInfo == null)
                {
                    return ReturnDataHelper<BackProgramConfigInfo>.Success("操作成功", null);
                }

                //生成Json文件
                new ProjectInfoBLL(_configuration).CreateJsonFile(projectInfo, cNameSpace);

                BackProgramConfigInfo result = ProjectInfoBLL.GetConfigInfoFromJsonFile(projectInfo.ProjectName, cNameSpace.NameSpace, nowTime);

                //删除过期的版本信息
                CNameSpaceBLL nameSpaceBLL = new CNameSpaceBLL(_configuration);
                nameSpaceBLL.DeleteExpiredVersionData(cNameSpace.ID);

                return ReturnDataHelper<BackProgramConfigInfo>.Success("操作成功", result);
            }
            catch (Exception ex)
            {
                Log4NetHelper.WriteExceptionLog("VersionRollBack,版本回滚", ex);
                return ReturnDataHelper<BackProgramConfigInfo>.Exception("系统异常", null);
            }
        }

        /// <summary>
        /// 获取配置历史信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ReturnData<List<ConfigInfoHistoryModel>> GetConfigInfoHistory(GetConfigInfoHistoryInput input)
        {
            try
            {
                if (!_versionsService.Exists(input.VersionID))
                {
                    return ReturnDataHelper<List<ConfigInfoHistoryModel>>.NoExists("版本信息不存在", null);
                }

                var result = _configInfoHistoryService.GetListByVersionId(input.VersionID)
                    .Select(w => new ConfigInfoHistoryModel()
                    {
                        ConfigKey = w.ConfigKey,
                        ConfigValue = w.ConfigValue,
                        ConfigDescription = w.ConfigDescription,
                    }).ToList();

                return ReturnDataHelper<List<ConfigInfoHistoryModel>>.Success("操作成功", result);
            }
            catch (Exception ex)
            {
                Log4NetHelper.WriteExceptionLog("GetConfigInfoHistory,获取配置历史信息", ex);
                return ReturnDataHelper<List<ConfigInfoHistoryModel>>.Exception("系统异常", null);
            }
        }
    }
}
